package com.reformer.commons.utils;

import com.reformer.commons.constant.ErrorMsg;
import com.reformer.commons.constant.KeyType;
import com.reformer.commons.constant.SignType;
import com.reformer.commons.exception.ResultException;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;

public abstract class KeyTool {
    /**
     * 生成私钥、公钥
     *
     * @param keytype
     * @return {私钥，公钥}
     * @throws Exception
     */
    public static String[] generateKey(KeyType keytype) throws Exception {
        KeyPairGenerator keyPairGenerator;
        try {
            keyPairGenerator = KeyPairGenerator.getInstance(keytype.getName());
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("不支持的算法名称：" + keytype.getName());
        }
        SecureRandom secureRandom = new SecureRandom();
        keyPairGenerator.initialize(keytype.getLength(), secureRandom);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        PrivateKey privateKey = keyPair.getPrivate();
        PublicKey publicKey = keyPair.getPublic();

        String[] result = new String[2];
        result[0] = Base64.encode(privateKey.getEncoded());
        result[1] = Base64.encode(publicKey.getEncoded());
        return result;
    }

    /**
     * 检查密钥
     *
     * @param keytype
     * @param privateKeyData
     * @param publicKeyData
     * @return
     */
    public static boolean checkKey(KeyType keytype, String privateKeyData, String publicKeyData) {
        SignType signType;
        if ("RSA".equals(keytype.getName())) {
            signType = SignType.RSA_SHA1;
        } else if ("DSA".equals(keytype.getName())) {
            signType = SignType.DSA;
        } else {
            throw new IllegalArgumentException();
        }
        String text = "abcdefghijklmknopq";
        String sign = null;
        try {
            sign = SignatureUtil.sign(signType, text, privateKeyData, "GBK");
        } catch (Exception e) {
            throw new ResultException(ErrorMsg.FILE_FORMAT_ERROR.getErrno(), "私钥内容不正确：" + e.getMessage());
        }
        try {
            return SignatureUtil.verify(signType, text, publicKeyData, sign, "GBK");
        } catch (Exception e) {
            throw new ResultException(ErrorMsg.FILE_FORMAT_ERROR.getErrno(), "公钥内容不正确：" + e.getMessage());
        }
    }
}